let express = require("express");
let uunewid = require("uuid");
const moment = require("moment");
let router = express.Router();
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_PRIVATE_COMMENTS";
const ohana_instance = new ohana(tableName);

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

router.get("/", function (req, res, next) {
    // #swagger.tags = ['私人留言']
    // #swagger.summary = '获取列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    let { TYPE, COMMENTER_ID, PID } = req.query;
    if (TYPE) {
        payload.TYPE = TYPE;
    }
    if (COMMENTER_ID) {
        payload.COMMENTER_ID = COMMENTER_ID;
    }
    if (PID) {
        payload.PID = PID;
    }

    getData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.post("/", function (req, res, next) {
    // #swagger.tags = ['私人留言']
    // #swagger.summary = '插入列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/privateComments_add"
                          }  
                      },
                  }
          } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let { data } = req.body;
    data.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    // IF_REPLY = true 说明是admin回复，使用传进来的COMMENTER_ID
    // IF_REPLY = false 使用token的userid
    if (!data.IF_REPLY) {
        data.COMMENTER_ID = user.user_id;
    }

    getOWNER_ID(data)
        .then((OWNER_ID) => {
            data.OWNER_ID = OWNER_ID;
            insertData(data)
                .then((result) => {
                    if (result == 1) {
                        res.sendStatus(200);
                    } else {
                        res.sendStatus(400);
                    }
                })
                .catch((err) => {
                    log.error(err);
                    res.status(500).send(err);
                });
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getOWNER_ID(condition) {
    let TYPE = condition.TYPE;
    let PID = condition.PID;
    switch (TYPE) {
        case "TA":
            sqlString =
                "select USER_ID_USER_ID from SAP_JIANGDU_TALENTS  where TALENT_ID ='" +
                PID +
                "'";
            break;
        case "PO":
            sqlString =
                'select USER_ID_USER_ID  from  "SAP_JIANGDU_POLICYS"  where POLICY_ID =\'' +
                PID +
                "'";
            break;
        case "FI":
            sqlString =
                'select USER_ID_USER_ID  from "SAP_JIANGDU_JINRONGHUIQIS"   where FIN_ID =\'' +
                PID +
                "'";
            break;
        case "TE":
            sqlString =
                'select USER_ID_USER_ID  from "SAP_JIANGDU_TECH_INNOS"  where TECH_ID =\'' +
                PID +
                "'";
            break;
        case "AS":
            sqlString =
                'select USER_ID_USER_ID  from "SAP_JIANGDU_ASSETS"  where ASSET_ID =\'' +
                PID +
                "'";
            break;
        default:
            break;
    }
    const resultData = await ohana_instance.raw(sqlString);
    if (resultData.length > 0) {
        return resultData[0].USER_ID_USER_ID;
    } else {
        return "所选服务中没有对应ID";
    }
}

router.put("/", function (req, res, next) {
    // #swagger.tags = ['私人留言']
    // #swagger.summary = '更新列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/privateComments_update"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    updateData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['私人留言']
    // #swagger.summary = '删除列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/privateComments_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    deleteData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(400);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getData(condition) {
    let result = [];
    result = await ohana_instance.find(condition);
    return result;
}

async function insertData(data) {
    data.PRIVATE_COMMENT_ID = uunewid.v4();
    let result = await ohana_instance.insert(data);
    return result;
}

async function updateData(data) {
    let result = await ohana_instance.update(
        {
            PRIVATE_COMMENT_ID: data.PRIVATE_COMMENT_ID,
        },
        data
    );
    return result;
}

async function deleteData(data) {
    let result = ohana_instance.raw(
        'delete from "' +
        tableName +
        "\" where PRIVATE_COMMENT_ID = '" +
        data.PRIVATE_COMMENT_ID +
        "'"
    );
    return result;
}

module.exports = router;
